<template>
  <div class="permission-management">
    <div class="page-header">
      <h1>权限管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新增权限
        </el-button>
      </div>
    </div>

    <el-tabs v-model="activeTab" class="permission-tabs">
      <!-- 权限列表 -->
      <el-tab-pane label="权限列表" name="permissions">
        <div class="table-container">
          <div class="table-header">
            <el-input
              v-model="searchText"
              placeholder="搜索权限名称或代码"
              style="width: 300px"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="filterModule" placeholder="选择模块" clearable style="width: 200px; margin-left: 10px">
              <el-option
                v-for="module in modules"
                :key="module.value"
                :label="module.label"
                :value="module.value"
              />
            </el-select>
          </div>

          <el-table :data="filteredPermissions" stripe>
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="权限名称" />
            <el-table-column prop="code" label="权限代码" />
            <el-table-column label="模块">
              <template #default="{ row }">
                {{ row.module_display || row.module }}
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="is_active" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.is_active ? 'success' : 'danger'">
                  {{ row.is_active ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button size="small" @click="editPermission(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deletePermission(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 角色权限 -->
      <el-tab-pane label="角色权限" name="roles">
        <div class="role-permissions">
          <div class="role-selector">
            <el-select v-model="selectedRole" placeholder="选择角色" style="width: 200px">
              <el-option label="管理员" value="admin" />
              <el-option label="调度员" value="dispatcher" />
              <el-option label="维修工" value="worker" />
              <el-option label="仓库管理员" value="warehouse_manager" />
            </el-select>
            <el-button type="primary" @click="loadRolePermissions" :disabled="!selectedRole">
              查看权限
            </el-button>
          </div>

          <div v-if="selectedRole" class="permissions-tree">
            <div class="tree-header">
              <h3>{{ selectedRole }} 的权限配置</h3>
              <el-button type="primary" @click="saveRolePermissions">保存配置</el-button>
            </div>
            <el-tree
              ref="permissionTree"
              :data="permissionTreeData"
              :props="treeProps"
              show-checkbox
              node-key="id"
              :default-checked-keys="checkedPermissions"
              @check="handlePermissionCheck"
            />
          </div>
        </div>
      </el-tab-pane>

      <!-- 用户权限 -->
      <el-tab-pane label="用户权限" name="users">
        <div class="user-permissions">
          <div class="user-selector">
            <el-select
              v-model="selectedUserId"
              placeholder="选择用户"
              style="width: 300px"
              filterable
              remote
              :remote-method="searchUsers"
            >
              <el-option
                v-for="user in users"
                :key="user.id"
                :label="`${user.name} (${user.username})`"
                :value="user.id"
              />
            </el-select>
            <el-button type="primary" @click="loadUserPermissions" :disabled="!selectedUserId">
              查看权限
            </el-button>
          </div>

          <div v-if="selectedUserId" class="user-permission-details">
            <h3>用户特殊权限</h3>
            <el-table :data="userPermissions">
              <el-table-column prop="name" label="权限名称" />
              <el-table-column prop="code" label="权限代码" />
              <el-table-column prop="module_display" label="模块" />
              <el-table-column prop="source" label="权限来源" width="120">
                <template #default="{ row }">
                  <el-tag :type="row.source === 'role' ? 'info' : 'success'">
                    {{ row.source === 'role' ? '角色权限' : '特殊权限' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button 
                    v-if="row.source === 'user'" 
                    size="small" 
                    type="danger" 
                    @click="removeUserPermission(row)"
                  >
                    移除
                  </el-button>
                  <span v-else class="text-gray-400">-</span>
                </template>
              </el-table-column>
            </el-table>
            
            <div class="add-permission">
              <el-button type="primary" @click="showAddUserPermissionDialog = true">
                添加特殊权限
              </el-button>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建/编辑权限对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingPermission ? '编辑权限' : '新增权限'"
      width="600px"
    >
      <el-form :model="permissionForm" :rules="permissionRules" ref="permissionFormRef" label-width="100px">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" />
        </el-form-item>
        <el-form-item label="权限代码" prop="code">
          <el-input v-model="permissionForm.code" />
        </el-form-item>
        <el-form-item label="模块" prop="module">
          <el-input v-model="permissionForm.module" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="permissionForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="permissionForm.is_active" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="savePermission">保存</el-button>
      </template>
    </el-dialog>

    <!-- 添加用户权限对话框 -->
    <el-dialog v-model="showAddUserPermissionDialog" title="添加用户权限" width="500px">
      <el-form :model="userPermissionForm" label-width="100px">
        <el-form-item label="权限">
          <el-select v-model="userPermissionForm.permission_id" placeholder="选择权限" style="width: 100%">
            <el-option
              v-for="permission in permissions"
              :key="permission.id"
              :label="permission.name"
              :value="permission.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="授权类型">
          <el-radio-group v-model="userPermissionForm.is_granted">
            <el-radio :label="true">授权</el-radio>
            <el-radio :label="false">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="过期时间">
          <el-date-picker
            v-model="userPermissionForm.expires_at"
            type="datetime"
            placeholder="选择过期时间（可选）"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddUserPermissionDialog = false">取消</el-button>
        <el-button type="primary" @click="addUserPermission">添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import {
  permissionsApi,
  usersApi,
  type Permission,
  type RolePermission,
  type UserPermission
} from '@/api'

// 响应式数据
const activeTab = ref('permissions')
const permissions = ref<Permission[]>([])
const searchText = ref('')
const filterModule = ref('')
const modules = ref<string[]>([])
const showCreateDialog = ref(false)
const editingPermission = ref<Permission | null>(null)

// 角色权限相关
const selectedRole = ref('')
const permissionTreeData = ref([])
const checkedPermissions = ref<number[]>([])
const permissionTree = ref()
const treeProps = {
  children: 'children',
  label: 'name'
}

// 用户权限相关
const selectedUserId = ref<number | null>(null)
const users = ref<any[]>([])
const userPermissions = ref<UserPermission[]>([])
const showAddUserPermissionDialog = ref(false)

// 表单数据
const permissionForm = reactive({
  name: '',
  code: '',
  module: '',
  description: '',
  is_active: true
})

const userPermissionForm = reactive({
  permission_id: null,
  is_granted: true,
  expires_at: null
})

// 表单验证规则
const permissionRules = {
  name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入权限代码', trigger: 'blur' }],
  module: [{ required: true, message: '请输入模块名称', trigger: 'blur' }]
}

// 计算属性
const filteredPermissions = computed(() => {
  let result = permissions.value
  
  if (searchText.value) {
    result = result.filter(p => 
      p.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
      p.code.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
  
  if (filterModule.value) {
    result = result.filter(p => p.module === filterModule.value)
  }
  
  return result
})

// 方法
const loadPermissions = async () => {
  try {
    const response = await permissionsApi.getPermissions()
    permissions.value = response.data.permissions || response.data
    
    // 提取模块列表，使用中文显示名称
    const moduleMap = new Map()
    permissions.value.forEach(p => {
      if (!moduleMap.has(p.module)) {
        moduleMap.set(p.module, {
          value: p.module,
          label: p.module_display || p.module
        })
      }
    })
    modules.value = Array.from(moduleMap.values())
  } catch (error) {
    ElMessage.error('加载权限列表失败')
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const editPermission = (permission: Permission) => {
  editingPermission.value = permission
  Object.assign(permissionForm, permission)
  showCreateDialog.value = true
}

const deletePermission = async (permission: Permission) => {
  try {
    await ElMessageBox.confirm('确定要删除这个权限吗？', '确认删除', {
      type: 'warning'
    })
    
    await permissionsApi.deletePermission(permission.id)
    ElMessage.success('删除成功')
    loadPermissions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const savePermission = async () => {
  try {
    if (editingPermission.value) {
      await permissionsApi.updatePermission(editingPermission.value.id, permissionForm)
      ElMessage.success('更新成功')
    } else {
      await permissionsApi.createPermission(permissionForm)
      ElMessage.success('创建成功')
    }
    
    showCreateDialog.value = false
    editingPermission.value = null
    resetPermissionForm()
    loadPermissions()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const resetPermissionForm = () => {
  Object.assign(permissionForm, {
    name: '',
    code: '',
    module: '',
    description: '',
    is_active: true
  })
}

const loadRolePermissions = async () => {
  try {
    const response = await permissionsApi.getRolePermissions(selectedRole.value)
    const rolePermissions = response.data.permissions || response.data
    
    // 构建权限树
    buildPermissionTree()
    
    // 设置已选中的权限
    checkedPermissions.value = rolePermissions
      .filter(rp => rp.has_permission)
      .map(rp => rp.id)
  } catch (error) {
    ElMessage.error('加载角色权限失败')
  }
}

const buildPermissionTree = () => {
  const moduleMap = new Map()
  
  permissions.value.forEach(permission => {
    if (!moduleMap.has(permission.module)) {
      moduleMap.set(permission.module, {
        id: `module_${permission.module}`,
        name: permission.module_display || permission.module,
        children: []
      })
    }
    
    moduleMap.get(permission.module).children.push({
      id: permission.id,
      name: permission.name,
      code: permission.code
    })
  })
  
  permissionTreeData.value = Array.from(moduleMap.values())
}

const handlePermissionCheck = (data: any, checked: any) => {
  // 处理权限选择
}

const saveRolePermissions = async () => {
  try {
    if (!permissionTree.value) {
      ElMessage.error('权限树组件未加载')
      return
    }
    
    const checkedNodes = permissionTree.value.getCheckedNodes()
    const permissionIds = checkedNodes
      .filter((node: any) => typeof node.id === 'number')
      .map((node: any) => node.id)
    
    const permissionData = permissions.value.map(p => ({
      permission_id: p.id,
      is_granted: permissionIds.includes(p.id)
    }))
    
    await permissionsApi.batchSetRolePermissions({
      role: selectedRole.value,
      permissions: permissionData
    })
    
    ElMessage.success('角色权限保存成功')
  } catch (error) {
    console.error('保存角色权限失败:', error)
    ElMessage.error('保存角色权限失败')
  }
}

const searchUsers = async (query: string) => {
  try {
    const response = await usersApi.getUsers({
      search: query,
      per_page: 20 // 限制返回数量
    })
    users.value = response.data.users || response.data
  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
    users.value = []
  }
}

const loadUserPermissions = async () => {
  try {
    const response = await permissionsApi.getUserPermissions(selectedUserId.value!)
    userPermissions.value = response.data.permissions || response.data
  } catch (error) {
    ElMessage.error('加载用户权限失败')
  }
}

const addUserPermission = async () => {
  try {
    // 获取当前用户的所有特殊权限ID
    const currentUserPermissions = userPermissions.value
      .filter(p => p.source === 'user')
      .map(p => p.id)
    
    // 添加新权限ID
    const newPermissionIds = [...currentUserPermissions, userPermissionForm.permission_id!]
    
    await permissionsApi.setUserPermission({
      user_id: selectedUserId.value!,
      permission_ids: newPermissionIds
    })
    
    ElMessage.success('添加用户权限成功')
    showAddUserPermissionDialog.value = false
    loadUserPermissions()
  } catch (error) {
    ElMessage.error('添加用户权限失败')
  }
}

const removeUserPermission = async (permission: any) => {
  try {
    await ElMessageBox.confirm('确定要移除这个特殊权限吗？', '确认移除', {
      type: 'warning'
    })
    
    // 获取当前用户的所有特殊权限ID，排除要删除的权限
    const currentUserPermissions = userPermissions.value
      .filter(p => p.source === 'user' && p.id !== permission.id)
      .map(p => p.id)
    
    // 重新设置用户权限（不包含被删除的权限）
    await permissionsApi.setUserPermission({
      user_id: selectedUserId.value!,
      permission_ids: currentUserPermissions
    })
    
    ElMessage.success('移除成功')
    loadUserPermissions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移除失败')
    }
  }
}

// 生命周期
onMounted(() => {
  loadPermissions()
  // 初始加载一些用户选项
  searchUsers('')
})
</script>

<style scoped>
.permission-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.permission-tabs {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.table-container {
  margin-top: 20px;
}

.table-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.role-permissions {
  margin-top: 20px;
}

.role-selector {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.permissions-tree {
  margin-top: 20px;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.user-permissions {
  margin-top: 20px;
}

.user-selector {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.user-permission-details {
  margin-top: 20px;
}

.add-permission {
  margin-top: 20px;
  text-align: center;
}
</style>